import bpy
import os
dir_path = 'C:/Users/zhangXX/Music/jntm'
output_dir = 'C:/Users/zhangXX/Music/jntm2'

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()


for file in os.listdir(dir_path):
    if file.endswith('.stl') or file.endswith('.STL'):
        file_path = os.path.join(dir_path, file)
        output_file_path = os.path.join(output_dir, file)

        bpy.ops.wm.stl_import(filepath=file_path)
        

        if bpy.context.selected_objects:
            obj = bpy.context.active_object
            obj.data = obj.data.copy()
            bpy.context.view_layer.objects.active = obj 

            mod = obj.modifiers.new(name="Decimator", type='DECIMATE')
            mod.ratio = 0.3
            #mod.levels = 2  
            bpy.ops.object.modifier_apply(modifier="Decimator")
            
            
            mat = bpy.data.materials.new(name="GreenMaterial")
            mat.diffuse_color = (0.12, 0.698, 0.69, 1)  
            obj.data.materials.append(mat)


            bpy.ops.wm.stl_export(filepath=output_file_path)

            bpy.ops.object.select_all(action='DESELECT')
            bpy.ops.object.select_by_type(type='MESH')
            bpy.ops.object.delete()

print("...")